const app = getApp()
const api = require('../../../../utils/api')

Page({
  data: {
    currentStatus: 0, // 0: 全部, 1: 新订单, 2: 处理中, 3: 已发货, 4: 已完成, 5: 已取消
    orders: [],
    loading: false,
    loadingMore: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    // 商家订单状态映射表
    statusMap: {
      1: '新订单',
      2: '处理中',
      3: '已发货',
      4: '已完成',
      5: '已取消'
    }
  },

  onLoad(options) {
    // 如果有状态参数，切换到对应标签
    if (options.status) {
      this.setData({
        currentStatus: parseInt(options.status)
      });
    }
    this.loadOrders();
  },

  onShow() {
    // 每次显示页面时刷新订单列表
    this.setData({
      page: 1,
      orders: [],
      hasMore: true
    });
    this.loadOrders();
  },

  // 切换订单状态
  async switchStatus(e) {
    const status = parseInt(e.currentTarget.dataset.status);
    if (status !== this.data.currentStatus) {
      this.setData({
        currentStatus: status,
        page: 1,
        orders: [],
        hasMore: true
      });
      await this.loadOrders();
    }
  },

  // 加载订单列表
  async loadOrders() {
    if (this.data.loading || !this.data.hasMore) return;

    try {
      this.setData({ loading: true });
      
      const params = {
        page: this.data.page - 1, // 后端分页从0开始
        size: this.data.pageSize
      };

      // 如果是"全部"状态，传undefined让后端返回所有订单
      const status = this.data.currentStatus === 0 ? undefined : this.data.currentStatus;
      const res = await api.getMerchantOrders(status, params);
      
      if (res.success) {
        const newOrders = res.data.content.map(order => ({
          ...order,
          statusText: this.data.statusMap[order.status],
          products: order.orderItems.map(item => ({
            id: item.productId,
            name: item.productName,
            price: item.productPrice,
            quantity: item.quantity,
            imageUrl: item.product?.imageUrl || '/images/default-product.png'
          }))
        }));
        
        this.setData({
          orders: this.data.page === 1 ? newOrders : [...this.data.orders, ...newOrders],
          hasMore: newOrders.length === this.data.pageSize,
          page: this.data.page + 1
        });
      } else {
        wx.showToast({
          title: res.message || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载订单失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 下拉刷新
  async onPullDownRefresh() {
    this.setData({
      page: 1,
      orders: [],
      hasMore: true
    });
    await this.loadOrders();
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  async onReachBottom() {
    if (this.data.hasMore) {
      await this.loadOrders();
    }
  },

  // 格式化价格
  formatPrice(price) {
    return parseFloat(price).toFixed(2)
  },

  // 获取订单状态文本
  getStatusText(status) {
    return this.data.statusMap[status] || '未知状态'
  },

  // 查看订单详情
  onViewDetail(e) {
    const { orderNo } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/merchant/order/detail/detail?orderNo=${orderNo}`
    })
  },

  // 接单
  async onAcceptOrder(e) {
    const { orderNo } = e.currentTarget.dataset
    await this.updateOrderStatus(orderNo, 2, '商家已接单');
  },

  // 发货
  async onShipOrder(e) {
    const { orderNo } = e.currentTarget.dataset
    await this.updateOrderStatus(orderNo, 3, '商家已发货');
  },

  // 完成订单
  async onCompleteOrder(e) {
    const { orderNo } = e.currentTarget.dataset
    await this.updateOrderStatus(orderNo, 4, '订单已完成');
  },

  // 取消订单
  async onCancelOrder(e) {
    const { orderNo } = e.currentTarget.dataset
    await this.updateOrderStatus(orderNo, 5, '商家已取消订单');
  },

  // 更新订单状态
  async updateOrderStatus(orderNo, status, notes) {
    try {
      const res = await api.updateMerchantOrderStatus(orderNo, status, notes);
      if (res.success) {
        wx.showToast({
          title: '操作成功',
          icon: 'success'
        });
        // 重新加载订单列表
        this.setData({
          page: 1,
          orders: [],
          hasMore: true
        });
        this.loadOrders();
      } else {
        wx.showToast({
          title: res.message || '操作失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('更新订单状态失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  }
}) 